#include "../include/services.h"
#include "../include/userCenterDao.h"
#include "../include/email_sender.h"

//获取验证码函数
std::string generateVerificationCode(int length) {
    static const std::string charset = 
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    
    // 使用随机设备和 Mersenne Twister 引擎
    static std::random_device rd;
    static std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, charset.size() - 1);
    
    std::string code;
    code.reserve(length);
    
    for (int i = 0; i < length; ++i) {
        code += charset[dis(gen)];
    }
    
    return code;    //会有返回值优化
}

::grpc::Status userCenterServices::GetVarifyCode(::grpc::ServerContext* context, const ::message::reqGetVarify* request, ::message::resGetVarify* response){
       
    //生成一个随机六位数字-----
    std::string code=generateVerificationCode();
    MyRedis* one=redis_pool::get_instance()->get_one_redis();
    if(one==nullptr){
        response->set_result("false");
        std::cout<<"redis_pool返回的实例为空！！"<<std::endl;
        return  grpc::Status::OK;
    }
    std::cout<<request->email()<<"  "<<code.c_str()<<std::endl;
    bool flag=one->setExNx(request->email().c_str(),code.c_str(),EXPIRETIME);
    if(!flag){
        response->set_result(false);
    }
    if(redis_pool::get_instance()->give_back_one_redis(one)){
        std::cout<<"放回成功"<<std::endl;
    }
    //填充response,并返回即可
    //执行真正的邮箱发送
    if(flag){
        //发送邮箱
        bool send_res=email_sender::get_instance()->send_email_plain_text(request->email(),"验证码","验证码为:"+code+"有效时间：180s  请及时查收使用\n如果不是本人操作，请忽略");
        if(send_res==false){
            response->set_result(false);
        }else{
            response->set_code(code);
            response->set_email(request->email());
            response->set_result(true);
        }
    }
    
    return grpc::Status::OK;

}


::grpc::Status userCenterServices::RegisterUser(::grpc::ServerContext* context, const ::message::reqRegisterUser* request, ::message::resRegisterUser* response){
    //
    userCenterDao::get_instance()->register_user(request,response);
    return grpc::Status::OK;
}

::grpc::Status userCenterServices::ResetPasswd(::grpc::ServerContext* context, const ::message::reqResetPasswd* request, ::message::resResetPasswd* response){
    //std::cout<<"进入重置密码的rpc调用"<<std::endl;
    userCenterDao::get_instance()->reset_passwd(request,response);
    return grpc::Status::OK;

}
::grpc::Status userCenterServices::Login(::grpc::ServerContext* context, const ::message::reqLogin* request, ::message::resLogin* response){
    std::cout<<"进入登陆的rpc调用"<<std::endl;
    userCenterDao::get_instance()->login(request,response);
    return grpc::Status::OK;
}